const Router = require('koa-router');
const pool = require('../db');
const router = new Router();

// 获取用户收藏列表
router.get('/favorites/:user_id', async (ctx) => {
  try {
    const { user_id } = ctx.params;
    const { page = 1, limit = 20 } = ctx.query;
    const offset = (page - 1) * limit;
    
    const [favorites] = await pool.execute(`
      SELECT s.*, uf.created_at as favorited_at
      FROM songs s
      JOIN user_favorites uf ON s.id = uf.song_id
      WHERE uf.user_id = ?
      ORDER BY uf.created_at DESC
      LIMIT ? OFFSET ?
    `, [user_id, parseInt(limit), offset]);
    
    // 获取总数
    const [countResult] = await pool.execute(
      'SELECT COUNT(*) as total FROM user_favorites WHERE user_id = ?',
      [user_id]
    );
    const total = countResult[0].total;
    
    ctx.body = {
      code: 0,
      message: 'success',
      data: {
        favorites,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total,
          pages: Math.ceil(total / limit)
        }
      }
    };
  } catch (error) {
    console.error('获取收藏列表失败:', error);
    ctx.body = { code: -1, message: '获取收藏列表失败' };
  }
});

// 添加收藏
router.post('/favorites', async (ctx) => {
  try {
    const { user_id, song_id } = ctx.request.body;
    
    if (!user_id || !song_id) {
      ctx.body = { code: -1, message: '用户ID和歌曲ID不能为空' };
      return;
    }
    
    // 检查歌曲是否存在
    const [songs] = await pool.execute('SELECT id FROM songs WHERE id = ?', [song_id]);
    if (songs.length === 0) {
      ctx.body = { code: -1, message: '歌曲不存在' };
      return;
    }
    
    await pool.execute(
      'INSERT INTO user_favorites (user_id, song_id) VALUES (?, ?)',
      [user_id, song_id]
    );
    
    ctx.body = {
      code: 0,
      message: '添加收藏成功'
    };
  } catch (error) {
    if (error.code === 'ER_DUP_ENTRY') {
      ctx.body = { code: -1, message: '歌曲已在收藏列表中' };
    } else {
      console.error('添加收藏失败:', error);
      ctx.body = { code: -1, message: '添加收藏失败' };
    }
  }
});

// 取消收藏
router.delete('/favorites/:user_id/:song_id', async (ctx) => {
  try {
    const { user_id, song_id } = ctx.params;
    
    const [result] = await pool.execute(
      'DELETE FROM user_favorites WHERE user_id = ? AND song_id = ?',
      [user_id, song_id]
    );
    
    if (result.affectedRows === 0) {
      ctx.body = { code: -1, message: '收藏记录不存在' };
      return;
    }
    
    ctx.body = {
      code: 0,
      message: '取消收藏成功'
    };
  } catch (error) {
    console.error('取消收藏失败:', error);
    ctx.body = { code: -1, message: '取消收藏失败' };
  }
});

// 检查歌曲是否已收藏
router.get('/favorites/:user_id/:song_id', async (ctx) => {
  try {
    const { user_id, song_id } = ctx.params;
    
    const [favorites] = await pool.execute(
      'SELECT id FROM user_favorites WHERE user_id = ? AND song_id = ?',
      [user_id, song_id]
    );
    
    ctx.body = {
      code: 0,
      message: 'success',
      data: {
        is_favorited: favorites.length > 0
      }
    };
  } catch (error) {
    console.error('检查收藏状态失败:', error);
    ctx.body = { code: -1, message: '检查收藏状态失败' };
  }
});

// 批量添加收藏
router.post('/favorites/batch', async (ctx) => {
  try {
    const { user_id, song_ids } = ctx.request.body;
    
    if (!user_id || !Array.isArray(song_ids) || song_ids.length === 0) {
      ctx.body = { code: -1, message: '用户ID和歌曲ID列表不能为空' };
      return;
    }
    
    // 检查所有歌曲是否存在
    const placeholders = song_ids.map(() => '?').join(',');
    const [songs] = await pool.execute(
      `SELECT id FROM songs WHERE id IN (${placeholders})`,
      song_ids
    );
    
    if (songs.length !== song_ids.length) {
      ctx.body = { code: -1, message: '部分歌曲不存在' };
      return;
    }
    
    // 批量插入收藏记录
    const values = song_ids.map(song_id => [user_id, song_id]);
    await pool.execute(
      'INSERT IGNORE INTO user_favorites (user_id, song_id) VALUES ?',
      [values]
    );
    
    ctx.body = {
      code: 0,
      message: '批量添加收藏成功'
    };
  } catch (error) {
    console.error('批量添加收藏失败:', error);
    ctx.body = { code: -1, message: '批量添加收藏失败' };
  }
});

// 获取用户收藏统计
router.get('/favorites/:user_id/stats', async (ctx) => {
  try {
    const { user_id } = ctx.params;
    
    // 获取收藏总数
    const [countResult] = await pool.execute(
      'SELECT COUNT(*) as total FROM user_favorites WHERE user_id = ?',
      [user_id]
    );
    
    // 获取最近收藏的歌曲
    const [recentFavorites] = await pool.execute(`
      SELECT s.*, uf.created_at as favorited_at
      FROM songs s
      JOIN user_favorites uf ON s.id = uf.song_id
      WHERE uf.user_id = ?
      ORDER BY uf.created_at DESC
      LIMIT 5
    `, [user_id]);
    
    // 获取收藏最多的艺术家
    const [topArtists] = await pool.execute(`
      SELECT s.artist, COUNT(*) as count
      FROM songs s
      JOIN user_favorites uf ON s.id = uf.song_id
      WHERE uf.user_id = ?
      GROUP BY s.artist
      ORDER BY count DESC
      LIMIT 5
    `, [user_id]);
    
    ctx.body = {
      code: 0,
      message: 'success',
      data: {
        total_favorites: countResult[0].total,
        recent_favorites: recentFavorites,
        top_artists: topArtists
      }
    };
  } catch (error) {
    console.error('获取收藏统计失败:', error);
    ctx.body = { code: -1, message: '获取收藏统计失败' };
  }
});

module.exports = router;
